package com.powernode.controller;

import cn.hutool.core.date.DateUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.powernode.config.AliyunOssConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.UUID;

/**
 * @Description:
 * @Author: Tong Ziyu
 * @Date: 2025/2/6 12:19
 */

@RestController
@Api(tags = "文件上传接口")
@Slf4j
@RequestMapping("admin/file")
public class FileUploadController {

    @Autowired
    private AliyunOssConfig aliyunOssConfig;

    //@Autowired
    //private FileStorageService fileStorageService;

    /**
     * 上传文件要求:
     *  1.请求方式必须是post方式
     *  2.接收文件的类型是 MultipartFile
     *
     * @return
     */
    @ApiOperation("上传单个文件")
    @PostMapping("upload/element")
    public String uploadFile(MultipartFile file){
        // 创建文件名
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate now = LocalDate.now();
        String preFile = now.format(dateTimeFormatter);

        // 创建文件名
        UUID uuid = UUID.randomUUID();

        // 获取文件后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));

        // 填写Bucket名称，例如examplebucket。
        String bucketName = aliyunOssConfig.getBucketName();
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = preFile + "/" + uuid + suffix;


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(
                aliyunOssConfig.getEndpoint(),
                aliyunOssConfig.getAccessKeyId(),
                aliyunOssConfig.getAccessKeySecret()
        );
        URL url = null;
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(aliyunOssConfig.getBucketName(), objectName, file.getInputStream());

            // 上传图片
            PutObjectResult result = ossClient.putObject(putObjectRequest);

            // 拿到上传后的链接
            url = ossClient.generatePresignedUrl(bucketName, objectName, DateUtil.offsetDay(new Date(), 365 * 100));
        } catch (Exception ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url.toString();
    }

    ///**
    // * 上传文件要求:
    // *  1.请求方式必须是post方式
    // *  2.接收文件的类型是 MultipartFile
    // *
    // * @return
    // */
    //@ApiOperation("上传单个文件")
    //@PostMapping("upload/element")
    //public String uploadFileV2(MultipartFile file) throws IOException {
    //    // 创建文件名
    //    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    //    LocalDate now = LocalDate.now();
    //    String preFile = now.format(dateTimeFormatter);
    //
    //    // 创建文件名
    //    UUID uuid = UUID.randomUUID();
    //
    //    // 获取文件后缀
    //    String originalFilename = file.getOriginalFilename();
    //    String suffix = originalFilename.substring(originalFilename.lastIndexOf('.'));
    //
    //    String fileName = uuid.toString() + suffix;
    //
    //    // 上传到服务器
    //    String url = fileStorageService.uploadImgFile(preFile, fileName, file.getInputStream());
    //
    //
    //    return url;
    //
    //    //// 填写Bucket名称，例如examplebucket。
    //    //String bucketName = aliyunOssConfig.getBucketName();
    //    //// 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
    //    //String objectName = preFile + "/" + uuid + suffix;
    //    //
    //    //
    //    //// 创建OSSClient实例。
    //    //OSS ossClient = new OSSClientBuilder().build(
    //    //        aliyunOssConfig.getEndpoint(),
    //    //        aliyunOssConfig.getAccessKeyId(),
    //    //        aliyunOssConfig.getAccessKeySecret()
    //    //);
    //    //URL url = null;
    //    //try {
    //    //    // 创建PutObjectRequest对象。
    //    //    PutObjectRequest putObjectRequest = new PutObjectRequest(aliyunOssConfig.getBucketName(), objectName, file.getInputStream());
    //    //
    //    //    // 上传图片
    //    //    PutObjectResult result = ossClient.putObject(putObjectRequest);
    //    //
    //    //    // 拿到上传后的链接
    //    //    url = ossClient.generatePresignedUrl(bucketName, objectName, DateUtil.offsetDay(new Date(), 365 * 100));
    //    //} catch (Exception ce) {
    //    //    System.out.println("Caught an ClientException, which means the client encountered "
    //    //            + "a serious internal problem while trying to communicate with OSS, "
    //    //            + "such as not being able to access the network.");
    //    //    System.out.println("Error Message:" + ce.getMessage());
    //    //} finally {
    //    //    if (ossClient != null) {
    //    //        ossClient.shutdown();
    //    //    }
    //    //}
    //    //return url.toString();
    //}

}
